<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item  v-if="!props.rowData" label="合同编号" prop="contractCode">
        <el-input
          v-model="queryParams.contractCode"
          placeholder="请输入合同编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item v-if="!props.rowData" label="合同名称" prop="contractName">
        <el-input
          v-model="queryParams.contractName"
          placeholder="请输入合同名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
<!--      <el-form-item label="社会信用代码/纳税人识别号" prop="taxIdNumber">-->
<!--        <el-input-->
<!--          v-model="queryParams.taxIdNumber"-->
<!--          placeholder="请输入社会信用代码/纳税人识别号"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="联系电话" prop="contactPhone">-->
<!--        <el-input-->
<!--          v-model="queryParams.contactPhone"-->
<!--          placeholder="请输入联系电话"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="开户银行" prop="bankName">-->
<!--        <el-input-->
<!--          v-model="queryParams.bankName"-->
<!--          placeholder="请输入开户银行"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="开户账号" prop="bankAccount">-->
<!--        <el-input-->
<!--          v-model="queryParams.bankAccount"-->
<!--          placeholder="请输入开户账号"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="地址" prop="address">-->
<!--        <el-input-->
<!--          v-model="queryParams.address"-->
<!--          placeholder="请输入地址"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="发票号码" prop="invoiceNumber">-->
<!--        <el-input-->
<!--          v-model="queryParams.invoiceNumber"-->
<!--          placeholder="请输入发票号码"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="开票日期" prop="invoiceDate">-->
<!--        <el-date-picker-->
<!--          v-model="queryParams.invoiceDate"-->
<!--          value-format="YYYY-MM-DD HH:mm:ss"-->
<!--          type="daterange"-->
<!--          start-placeholder="开始日期"-->
<!--          end-placeholder="结束日期"-->
<!--          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"-->
<!--          class="!w-220px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="票种" prop="invoiceType">-->
<!--        <el-select-->
<!--          v-model="queryParams.invoiceType"-->
<!--          placeholder="请选择票种"-->
<!--          clearable-->
<!--          class="!w-240px"-->
<!--        >-->
<!--          <el-option-->
<!--            v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_INVOICE_TYPE)"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="特定业务" prop="specificBusiness">-->
<!--        <el-input-->
<!--          v-model="queryParams.specificBusiness"-->
<!--          placeholder="请输入特定业务"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="发票金额" prop="invoiceAmount">-->
<!--        <el-input-->
<!--          v-model="queryParams.invoiceAmount"-->
<!--          placeholder="请输入发票金额"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="税率" prop="taxRate">-->
<!--        <el-select-->
<!--          v-model="queryParams.taxRate"-->
<!--          placeholder="请选择税率"-->
<!--          clearable-->
<!--          class="!w-240px"-->
<!--        >-->
<!--          <el-option-->
<!--            v-for="dict in getDictOptions(DICT_TYPE.BIZ_INVOICE_TAX)"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="税金" prop="taxAmount">-->
<!--        <el-input-->
<!--          v-model="queryParams.taxAmount"-->
<!--          placeholder="请输入税金"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="不含税金额" prop="amountWithoutTax">-->
<!--        <el-input-->
<!--          v-model="queryParams.amountWithoutTax"-->
<!--          placeholder="请输入不含税金额"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="备注" prop="remarks">-->
<!--        <el-input-->
<!--          v-model="queryParams.remarks"-->
<!--          placeholder="请输入备注"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="销方银行" prop="sellerBank">-->
<!--        <el-select-->
<!--          v-model="queryParams.sellerBank"-->
<!--          placeholder="请选择销方银行"-->
<!--          clearable-->
<!--          class="!w-240px"-->
<!--        >-->
<!--          <el-option-->
<!--            v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_INVOICE_BANK)"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="更新时间" prop="updatedAt">-->
<!--        <el-date-picker-->
<!--          v-model="queryParams.updatedAt"-->
<!--          value-format="YYYY-MM-DD"-->
<!--          type="date"-->
<!--          placeholder="选择更新时间"-->
<!--          clearable-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="创建时间" prop="createTime">-->
<!--        <el-date-picker-->
<!--          v-model="queryParams.createTime"-->
<!--          value-format="YYYY-MM-DD HH:mm:ss"-->
<!--          type="daterange"-->
<!--          start-placeholder="开始日期"-->
<!--          end-placeholder="结束日期"-->
<!--          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"-->
<!--          class="!w-220px"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button  v-if="!props.rowData" @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button  v-if="!props.rowData" @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['invoice:biz-invoice-management:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['invoice:biz-invoice-management:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['invoice:biz-invoice-management:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
    <el-table-column type="selection" width="55" />
<!--      <el-table-column label="主键ID" align="center" prop="id" />-->
      <el-table-column label="合同编号" align="center" prop="contractCode" width="180" />
      <el-table-column label="合同名称" align="center" prop="contractName" width="180" />
      <el-table-column label="期数" align="center" prop="instalmentCount" width="80" />
      <el-table-column label="发票名称" align="center" prop="name" width="180"  />
      <el-table-column label="社会信用代码/纳税人识别号" align="center" prop="taxIdNumber" width="200"/>
      <el-table-column label="联系电话" align="center" prop="contactPhone" />
      <el-table-column label="开户银行" align="center" prop="bankName" />
      <el-table-column label="开户账号" align="center" prop="bankAccount" />
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column label="发票号码" align="center" prop="invoiceNumber" />
      <el-table-column
        label="开票日期"
        align="center"
        prop="invoiceDate"
        :formatter="dateFormatter2"
        width="120px"
      />
      <el-table-column label="票种" align="center" prop="invoiceType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.BIZ_INVOICE_TYPE" :value="scope.row.invoiceType" />
        </template>
      </el-table-column>
      <el-table-column label="特定业务" align="center" prop="specificBusiness">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.BIZ_INVOICE_BIZ" :value="scope.row.specificBusiness" />
        </template>
      </el-table-column>
      <el-table-column label="发票金额" align="center" prop="invoiceAmount" />
      <el-table-column label="税率" align="center" prop="taxRate">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.BIZ_INVOICE_TAX" :value="scope.row.taxRate" />%
        </template>
      </el-table-column>
      <el-table-column label="税金" align="center" prop="taxAmount" />
      <el-table-column label="不含税金额" align="center" prop="amountWithoutTax"  width="100"/>
      <el-table-column label="备注" align="center" prop="remarks" />
      <el-table-column label="销方银行" align="center" prop="sellerBank"/>
      <el-table-column label="发票状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.BIZ_INVOICE_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="签收人" align="center" prop="signName" />
      <el-table-column label="云开票状态" align="center" prop="cloudStatus" width="100" />
      <el-table-column label="作废时间" align="center" prop="cloudStatus" >
        <template #default="scope">
          {{formatDate(scope.row.cancelTime,'YYYY-MM-DD')}}
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updatedAt"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="审核状态" width="100" fixed="right" align="center" prop="approveStatus">
        <template #default="scope">
          <dict-tag  :title="'不通过原因：'+(scope.row.approveNo? scope.row.approveNo: '')"  :type="DICT_TYPE.BIZ_INVOICE_APPROVE_STATUS" :value="scope.row.approveStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center" min-width="180px">
        <template #default="scope">
          <el-button
            v-if="scope.row.approveStatus === 0 || scope.row.approveStatus === 3"
            link
            type="primary"
            @click="updateForm(scope.row.id,1)"
            v-hasPermi="['invoice:biz-invoice-management:update']"
          >
            提交
          </el-button>
          <el-button
            v-else-if="scope.row.approveStatus === 1 && checkRole(['biz_invoice_approve_role'])"
            link
            type="primary"
            @click="approveForm(scope.row.id)"
            v-hasPermi="['invoice:biz-invoice-management:update']"
          >
            审批
          </el-button>
          <el-button
            v-if="scope.row.approveStatus === 0 || scope.row.approveStatus === 3"
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['invoice:biz-invoice-management:update']"
          >
            编辑
          </el-button>
          <el-button
            v-if="scope.row.approveStatus === 0 || scope.row.approveStatus === 3"
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['invoice:biz-invoice-management:delete']"
          >
            删除
          </el-button>
          <el-button
            v-else
            link
            type="primary"
            @click="openForm('view', scope.row.id)"
            v-hasPermi="['invoice:biz-invoice-management:update']"
          >
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BizInvoiceManagementForm ref="formRef" @success="getList" />
  <el-dialog v-model="approveFormDialog" title="审批" width="500">
    <el-form :model="approveFormData">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="审批意见" label-width="120px">
            <el-radio-group v-model="approveFormData.approveStatus">
              <el-radio :value="2">同意</el-radio>
              <el-radio :value="3">不同意</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item v-show="approveFormData.approveStatus === 3" label="不同意原因" label-width="120px">
            <el-input v-model="approveFormData.approveNo" autocomplete="off" />
          </el-form-item>
          </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="approveFormDialog = false">取消</el-button>
        <el-button type="primary" @click="updateForm">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { getStrDictOptions,getDictOptions, DICT_TYPE } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter,dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { BizInvoiceManagementApi, BizInvoiceManagement } from '@/api/biz/invoice'
import BizInvoiceManagementForm from './BizInvoiceManagementForm.vue'
import { formatDate } from '@/utils/formatTime'
import { watch, ref } from 'vue'
import { checkPermi, checkRole } from "@/utils/permission"; // 权限判断函数

const props = defineProps<{
  rowData: object
}>()
const contractForm = ref({})
// 使用watch监听props变化
watch(() => props.rowData, (newVal) => {
  // 处理新的rowData
  contractForm.value = { ...newVal }
}, { deep: true, immediate: true })

// 监听路由参数变化
// import { useRoute } from 'vue-router'
const route = useRoute()
/** 发票管理 列表 */
defineOptions({ name: 'BizInvoiceManagement' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<BizInvoiceManagement[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  contractCode: props.contractCode,
  name: undefined,
  taxIdNumber: undefined,
  contactPhone: undefined,
  bankName: undefined,
  bankAccount: undefined,
  address: undefined,
  invoiceNumber: undefined,
  invoiceDate: [],
  invoiceType: undefined,
  specificBusiness: undefined,
  invoiceAmount: undefined,
  taxRate: undefined,
  taxAmount: undefined,
  amountWithoutTax: undefined,
  remarks: undefined,
  sellerBank: undefined,
  updatedAt: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// const contractForm = ref({})
/** 查询列表 */
const getList = async () => {
  loading.value = true
  console.info(contractForm.value)
  console.info(props.rowData)
  if( props.rowData){
    // console.info(contract)
    contractForm.value = props.rowData
    queryParams.contractReceiveRecordId = contractForm.value.id
    // console.info(contractForm.value)
  }
  try {
    const data = await BizInvoiceManagementApi.getBizInvoiceManagementPage(queryParams)
    list.value = data.records
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id,contractForm.value)
}

import { ElMessage, ElMessageBox } from 'element-plus'
import {a} from "vite/dist/node/types.d-jgA8ss1A";
/** 提交审批 */
const updateForm = async (id?: number, approveStatus?: number) => {
  if( id && approveStatus) {
    ElMessageBox.confirm(
      '是否确定要提交审批?',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(async () =>{
        const data = {id:id, approveStatus:approveStatus};
        await BizInvoiceManagementApi.updateBizInvoiceManagement(data)
          message.success(('提交成功'))
          // 刷新列表
        await getList()
      })
      .catch(() => {
      })
  } else {
    const data = approveFormData.value;
    await BizInvoiceManagementApi.updateBizInvoiceManagement(data);
    message.success(('提交成功'));
    approveFormDialog.value = false
    await getList();
  }

}

const approveFormDialog = ref(false)
const approveFormData = ref({
  id: undefined,
  approveStatus: undefined,
  approveNo: undefined
})
const approveForm =  async (id: number, approveStatus: number)  => {
  approveFormData.value.id = id
  approveFormData.value.approveStatus = approveStatus
  approveFormDialog.value = true
};

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BizInvoiceManagementApi.deleteBizInvoiceManagement(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除发票管理 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await BizInvoiceManagementApi.deleteBizInvoiceManagementList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: BizInvoiceManagement[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await BizInvoiceManagementApi.exportBizInvoiceManagement(queryParams)
    download.excel(data, '发票管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
// 暴露方法给父组件
defineExpose({
  getList,
  // close,
  queryParams
})
/** 初始化 **/
onMounted(() => {
  const contractReceiveRecordId = route.query.id
  if (contractReceiveRecordId) { // 只有存在 id 时才刷新
    queryParams.contractCode = contractReceiveRecordId
    getList()
  } else {
    getList()
  }
})
</script>
